package com.hundsun.aitest.service.impl;

import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.EntityListHandler;
import com.alibaba.fastjson.JSONArray;
import com.hundsun.aitest.model.plat.TableStruct;
import com.hundsun.aitest.service.DataBaseService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Data
@Slf4j
@Lazy
@Service
public class DataBaseServiceImpl implements DataBaseService {

    @Value("${spring.projects}")
    private String projects;

    private String project;

    private Map<String, DataSource> dataSourceMap = new HashMap<>();

    @Override
    public void initProject(String project) {
        String[] projectList = this.projects.split(",");
        this.project = project;
        List<String> list = Arrays.asList(projectList);
        boolean containsProject = list.contains(project);
        if(containsProject && dataSourceMap.get(project) == null){
            DataSource ds = DSFactory.get("group_" + project);
            dataSourceMap.put(project, ds);
        }else if(!containsProject){
            log.error("project is not exist!");
        }else{
            log.info("project and ds is exist!");
        }
    }

    @Override
    public List<Entity> actSql(String sql) {
        List<Entity> resultList = new ArrayList<>();
        if(project != null){
            DataSource dataSource = dataSourceMap.get(project);
            try (Connection connection = dataSource.getConnection();
                 PreparedStatement statement = connection.prepareStatement(sql);
                 ResultSet resultSet = statement.executeQuery()) {
                 EntityListHandler entityHandler = new EntityListHandler();
                 resultList = entityHandler.handle(resultSet);
                 log.info("result:{}", resultList);
            } catch (SQLException e) {
                 log.error("Error executing SQL: {}", sql, e);
            }
        }
        return resultList;
    }

    @Override
    public JSONArray parserSqlResult(List<Entity> entityList) {
        return null;
    }

    @Override
    public List<TableStruct> readTableStructure(String tableName) {
        String[] tableNameList = tableName.split("\\.");
        String sql = "select COLUMN_NAME, COLUMN_TYPE, COLUMN_COMMENT, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY from information_schema.columns t " +
                "where t.table_schema = '" + tableNameList[0] + "' and table_name = '"  + tableNameList[1] + "'";
        List<Entity> result = actSql(sql);
        log.info("result:{}", result);
        List<TableStruct> tableStructList = new ArrayList<>();
        for (Entity entity : result) {
            TableStruct tableStruct = new TableStruct();
            tableStruct.setName(entity.getStr("COLUMN_NAME"));
            tableStruct.setType(entity.getStr("COLUMN_TYPE"));
            tableStruct.setComment(entity.getStr("COLUMN_COMMENT"));
            tableStruct.setIsNullable(entity.getStr("IS_NULLABLE"));
            tableStruct.setDefaultValue(entity.getStr("COLUMN_DEFAULT"));
            tableStruct.setColumnKey(entity.getStr("COLUMN_KEY"));
            tableStructList.add(tableStruct);
        }
        log.info("tableStructList:{}", tableStructList);
        return tableStructList;
    }
}
